const app = getApp();
import Https from "../../utils/api.js"
const http = new Https
const util = require('../../utils/util.js')
Page({
  data: {
    myId: 2,
    userList: [],
    talks: [],
    user_id: 1,
    list: [
      {
        "pagePath": "/pages/home/home",
        "text": "首页",
        "iconPath": "/assets/tabbar/home_new.png",
        "selectedIconPath": "/assets/tabbar/home_new_.png",
        "selectedColor": "#3fbaa6"
      },
      {
        "pagePath": "/pages/chatList/chatList",
        "text": "消息",
        "redDot": wx.getStorageSync('num'),
        "iconPath": "/assets/tabbar/home_message.png",
        "selectedIconPath": "/assets/tabbar/home_message.png",
        "selectedColor": "#3fbaa6"
      },
      {
        "pagePath": "/pages/publish/publish",
        "text": "发布",
        "iconPath": "/assets/tabbar/mine_new.png",
        "selectedIconPath": "/assets/tabbar/mine_new_.png",
        "selectedColor": "#3fbaa6"
      },
      {
        "pagePath": "/pages/my/my",
        "text": "我的",
        "iconPath": "/assets/tabbar/news_new.png",
        "selectedIconPath": "/assets/tabbar/news_new_.png",
        "selectedColor": "#3fbaa6"
      }
    ]
  },

  goChat(e) {
    console.log(e)
    wx.navigateTo({
      url: '/pages/chat/chat?id=' + e.currentTarget.dataset.id + '&name=' + e.currentTarget.dataset.name,
    })
  },

  onLoad() {
    this.getUnread()
    wx.getStorageInfo({
      success: (option) => {
        console.log(option.keys)
        option.keys.forEach(element => {
          var message = wx.getStorageSync(element)
          console.log(message)
          var data = this.data.userList
          var str_reg = /^[a-zA-Z]([-_a-zA-Z0-9]{1,20})$/
          if (message.identity == 'user') {
            if (!str_reg.test(element)) {
              http.request('wx/user', {
                id: parseInt(element)
              }).then((res) => {
                console.log(res.data)
                var talk = wx.getStorageSync(element)
                var content = ''
                var num = 0
                var time = ''
                talk.forEach(e => {
                  num = num + 1
                  content = e.content
                  time = e.create_time
                });
                console.log(time)
                data.push({
                  ...res.data,
                  content: content,
                  num: num,
                  time: time,
                  identity:'user'
                })
                console.log(data)
                this.setData({
                  userList: data
                })
              })
            }
          } else {
            if (!str_reg.test(element)) {
              http.request('agent/agent', {
                id: parseInt(element)
              }).then((res) => {
                console.log(res.data)
                var talk = wx.getStorageSync(element)
                var content = ''
                var num = 0
                var time = ''
                talk.forEach(e => {
                  num = num + 1
                  content = e.content
                  time = e.create_time
                });
                console.log(time)
                data.push({
                  ...res.data,
                  content: content,
                  num: num,
                  time: time,
                  identity:'agent'
                })
                console.log(data)
                this.setData({
                  userList: data
                })
              })
            }
          }
        });
      }
    })
  },

  onShow: function () {
    wx.getStorageInfo({
      success: (option) => {
        console.log(option.keys)
        option.keys.forEach(element => {
          var str_reg = /^[a-zA-Z]([-_a-zA-Z0-9]{6,20})$/
          if (!str_reg.test(element)) {
            var data = wx.getStorageSync(element)
            var info = {
              [`${this.data.user_id}to${this.data.myId}`]: data
            }
            var talks = this.data.talks
            talks.push(info)
            this.setData({
              talks: talks
            })
          }
        });
      },
    })



    // let count = wx.getStorageSync(`chat${this.data.myId}to1`) || 0
    // if (content.length > 0) {
    //   this.setData({
    //     [`chat${this.data.myId}to1Time`]: content[(content.length-1)].time.substring(11,19),
    //     [`chat${this.data.myId}to1Content`]: content[(content.length-1)].content,
    //     chat2to1: count
    //   })
    // }



    let that = this;
    wx.onSocketOpen(function (res) {
    })

    //将获取到的聊天信息存入本地缓存
    wx.onSocketMessage(function (res) {
      console.log(res)
      var data = JSON.parse(res.data)
      let array = wx.getStorageSync(`${data.send_id}to${data.rec_id}`) || []
      array.push(data)
      wx.setStorageSync(data.send_id + "to" + data.rec_id, array)
      wx.getStorageInfo({
        success: (option) => {
          option.keys.forEach(element => {
            var str_reg = /^[a-zA-Z]([-_a-zA-Z0-9]{6,20})$/
            if (!str_reg.test(element)) {
              var talks = wx.getStorageSync(element)
              var id = element.slice(0, 1)
              var list = that.data.userList
              var num = 0
              for (const iterator of list) {
                if (iterator.id == id) {
                  talks.forEach(e => {
                    num = num + 1
                    iterator.content = e.content
                    iterator.time = e.create_time
                  });
                  iterator.num = num
                }
              }
              that.setData({
                userList: list
              })
            }
          });
        },
      })
    })
  },

  /**
   * 将获取到的聊天信息存入本地缓存
   * @param {*} message 
   */
  savaChatToLocal(message) {
    let that = this
    message.time = util.formatTime(new Date(message.createTime))
    let array = wx.getStorageSync(`${that.data.myId}to${message.sendId}`) || []
    array.push(message)
    wx.setStorageSync(`${that.data.myId}to${message.sendId}`, array)
    if (that.data[`chat${that.data.myId}to${message.sendId}`]) {
      that.setData({
        [`chat${that.data.myId}to${message.sendId}`]: that.data[`chat${that.data.myId}to${message.sendId}`] + 1
      })
    } else {
      that.setData({
        [`chat${that.data.myId}to${message.sendId}`]: 1
      })
    }
    that.setData({
      [`chat${that.data.myId}to${message.sendId}Time`]: message.time.substring(11, 19),
      [`chat${that.data.myId}to${message.sendId}Content`]: message.content
    })
    wx.setStorageSync(`chat${that.data.myId}to${message.sendId}`, that.data[`chat${that.data.myId}to${message.sendId}`])
  },

  getUnread() {
    let that = this
    // wx.request({
    //   url: 'http://localhost:18092/chat/unread/getUnread.do', 
    //   data: {id: this.data.myId},
    //   header: {
    //     'content-type': 'application/json' // 默认值
    //   },
    //   success (res) {
    //     console.log(res.data)
    //     for(let i of res.data) {
    //       that.savaChatToLocal(i)
    //     }
    //   },
    //   fail (res) {
    //     console.log(res.data)
    //   },
    // })
  }


})